package com.bxl.netty.rpc.server.handler;

import com.bxl.netty.rpc.common.builder.ResponseMsgBuilder;
import com.bxl.netty.rpc.common.context.Context;
import com.bxl.netty.rpc.common.message.MsgResponseContent;
import com.bxl.netty.rpc.common.message.PackageMsg;
import com.bxl.netty.rpc.common.message.RpcContent;
import com.bxl.netty.rpc.register.server.common.context.ServerContext;
import com.bxl.netty.rpc.server.context.BeanServerContext;
import com.bxl.netty.rpc.server.filter.FilterChain;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;


/**
 * <>
 *
 * @author baixl
 * @date 2021/2/23
 */
public class ServerHandler extends SimpleChannelInboundHandler<PackageMsg<RpcContent>> {
    private FilterChain filterChain;
    private BeanServerContext context;

    public ServerHandler() {

    }

    public ServerHandler(Context context) {
        assert context == null;
        this.context = (BeanServerContext) context;
        this.filterChain = this.context.getChain();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PackageMsg<RpcContent> msg) throws Exception {
        // 简单地打印出server接收到的消息
        System.out.println("接收:" + msg.getContent().getName());
        MsgResponseContent content = MsgResponseContent.successContent();
        try {
            this.filterChain.doFilter(msg, content, null);
        } catch (Exception e) {
            content = MsgResponseContent.failContent(e.getMessage());
        }
        ctx.writeAndFlush(ResponseMsgBuilder.createMsg(msg.getHeader().getFlag(), msg.getHeader().getRequestID(), content));
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception{
        System.out.println("断开连接 + "+ctx.channel().remoteAddress());
        ctx.disconnect();
    }

}
